//
//  SecurityTaskEditVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/17.
//
// 【首页-保安管理】保安管理任务详情

import Foundation
import UIKit

class SecurityTaskEditVC: SubLevelViewController {
    let listV = SecurityTaskDetailView()
    var modal: LzglbaListModel!
    var param = LzglSaveParam(lzrmc: BSUser.currentUser.nickName, lzrhm: BSUser.currentUser.userName)
    
    var locM: LocModal?
    
    init(withModal _modal: LzglbaListModel) {
        super.init(nibName: nil, bundle: nil)
        self.modal = _modal
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Override
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "任务详情"
        setupUI()
        
        reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        verifyLoc()
    }
    
    @objc func verifyLoc() {
        LocManager.shared.didUpdateLocWith = { (longitude, latitude, address) -> () in
            self.param.lng = longitude
            self.param.lat = latitude
            self.param.location = address
            self.locM = LocModal(location: address)
            self.updateLoc()
        }
        LocManager.shared.startLoaction()
    }
    
    func reloadData() {
         // 任务详情
        API.getLzglbaRwedit(withParam: SecurityParam(id: modal.id)) { responseModel in
            self.modal = responseModel.model
            DispatchQueue.main.async {
                self.listV.reload(withModal: responseModel.model)
            }
        }
    }
    
    func updateLoc() {
        let lngLat = "\(param.lng ?? ""),\(param.lat ?? "")"
        API.getConvert(withParam: SettingParam(lngLat: lngLat)) { responseModel in
            if responseModel.errorCode == .Success && responseModel.model?.location != "" {
                self.locM = responseModel.model
            }
            DispatchQueue.main.async {
                self.listV.updateLoc(withModal: self.locM)
            }
        }
    }
    
    // MARK: - Actions
    @objc func submitTapped() {
        
        let datas = self.modal?.rwjlMbDqList ?? []
        let listParams = listV.listParams
        
        var dateDatas: [SBoscLzglRwjlModal] = []
        
        for data in datas {
            let ds = data.boscLzglRwjlMbs?.filter({$0.xxlxdm == SCheckEffectEnum.date.rawValue}) ?? []
            if ds.count > 0 {
                dateDatas.append(contentsOf: ds)
            }
        }
        
        for data in dateDatas {
            let mbs = listParams.filter({ $0.id == data.id })
            if mbs.count == 0 {
                view.showToast(witMsg: "请完成「\(data.rwmc ?? "")」")
                return
            }
            
            for mb in mbs {
                if mb.remark == "" || mb.remark == nil {
                    view.showToast(witMsg: "请选择「\(data.rwmc ?? "")」")
                    return
                }
            }
        }
        
        view.showToastActivity()
        
        // 上传图片
        if listParams.count == 0 {
            self.didSubmint(withuploadParam: [])
            return
        }
        
        var uParam: [RwjlUploadParam] = []
        
        for listParam in listParams {
            if listParam.images?.count == 0 {
                uParam.append(RwjlUploadParam(id: listParam.id, rwid: listParam.rwid, answers: listParam.answers))
                if uParam.count == listParams.count {
                    self.didSubmint(withuploadParam: uParam)
                }
            } else {
                var uploadindex = 0
                var imageUrlList: [[String: String]] = []
                for img in listParam.images! {
                    let path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img)
                    API.lzglUpload(withImage: path!) { responseModel in
                        if responseModel.model?.imgUrl != nil {
                            imageUrlList.append(["fjdz": responseModel.model!.imgUrl!])
                        }
                        uploadindex += 1
                        if listParam.images!.count == uploadindex {
                            uParam.append(RwjlUploadParam(id: listParam.id, rwid: listParam.rwid, answers: listParam.answers, images: imageUrlList))
                            if uParam.count == listParams.count {
                                self.didSubmint(withuploadParam: uParam)
                            }
                        }
                    }
                }
            }
        }
    }
    
    func didSubmint(withuploadParam up: [RwjlUploadParam]) {
        param.id = modal.id
        param.rwid = modal.rwid
        param.batched = true
        param.rwjlMbList = up
        do {
            let data: Data = try JSONEncoder().encode(param)
            let string = String(data: data, encoding: String.Encoding.utf8)
            API.postLzglbaRwsave(withParam: CommonJsonParam(jsonStr: string)) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                    self.navigationController?.popViewController(animated: true)
                }
            }
        } catch {
            print("postLzglbaRwsave error", error)
        }
    }
    
    // MARK: - Setup
    func setupUI() {
        listV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        listV.locV.btn.addTarget(self, action: #selector(verifyLoc), for: .touchUpInside)
        view.addSubview(listV)
        listV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}
